#!/usr/bin/perl
#
use strict;
use warnings;
use Data::Dumper;
 
binmode STDOUT, ":utf8";
#use utf8;
 
use JSON;
use File::Copy;
require "doa_subs.pl";
use CGI;
use lib '.';
use users;

my ($username,$level) = &validate;
if ($level > 5) { &dienice("You must be an administrator to run this");}
my ($realm) = get_realm();
############################## Main Prog ##############################
my $q = new CGI;

print $q->header;
print $q->start_html(
	-title => "Process Activity Update file"
);

print $q->h1("process Activity update file");

my $player_id={};
my $player_name={};
my $hashcnt1=0;
my $hashcnt2=0;

my $outdata={};

my $player_count=loadPlayers($player_id,$player_name);
$hashcnt1=keys %{$player_id};
$hashcnt2=keys %{$player_name};
$outdata=loadMAP("mapfile");
print $q->p("initial player count $player_count playerid  $hashcnt1 player name $hashcnt2\n");

my @actFiles=readDir("activity");
#print Dumper(@actFiles);
foreach my $actfile (@actFiles)
{
	print $q->p("file $actfile\n");
	my ($fdate,$ftime,$timestring)=pfileDate($actfile);
	$outdata->{'update'}{'activity'}=$timestring;
	my $fullname="activity/".$actfile;
	my $data=readJSON($fullname);

	my $actarray = $data->{'activity'};

	foreach my $actref (@$actarray)
	{
		#print "pname $actref->{'pname'} aname $actref->{'aname'}\n";
    	$player_id->{$actref->{'pid'}}=$actref->{'pname'};
		$player_name->{$actref->{'pname'}}=$actref->{'pid'};
		$player_id->{$actref->{'aid'}}=$actref->{'aname'};
		$player_name->{$actref->{'aname'}}=$actref->{'aid'};
	}
	move("$fullname","processed_activity/$actfile") or die_nice ("Could not move $actfile to processed_activity directory");
}
$player_count=writePlayers($player_id);
$hashcnt1=keys %{$player_id};
$hashcnt2=keys %{$player_name};
print $q->p("after activity player count $player_count playerid  $hashcnt1 player name $hashcnt2\n");

$player_count=writePlayers($player_id);
$hashcnt1=keys %{$player_id};
$hashcnt2=keys %{$player_name};
print $q->p("after final write player count $player_count playerid  $hashcnt1 player name $hashcnt2\n");

writeMAP($outdata,"mapfile");

print $q->br();
print $q->a( {-href=>"menu.cgi"}, "Main Menu");
print $q->end_html;


